<template>
  <div class="orderDetial">
    <!-- <div class="orderDetial_top">工单详情页</div> -->
    <el-card>
      <div class="orderDetial_inner">
        <!-- <div class="orderDetial_title" style="height:30px">聊天界面</div> -->

        <div class="orderDetial_left">
          <div
            v-for="item in usermssageList"
            class="orderDetial_left_list"
            @click="handlerDetial(item)"
          >
            <div class="orderDetial_left_list_item">
              <div class="orderDetial_left_list_item_right_x">
                <div class="orderDetial_left_list_item_left">
                  <!-- <img
                    src="../../assets/images/aaa.jpg"
                    alt=""
                    class="head_img"
                  /> -->

                  {{
                    item.realName == null
                      ? "未知"
                      : item.realName.substring(item.realName.length - 2)
                  }}
                </div>
                <div class="orderDetial_left_list_item_center">
                  <div class="orderDetial_left_list_item_center_name">
                    {{ item.realName == null ? "未知" : item.realName }}
                  </div>
                  <div
                    class="orderDetial_left_list_item_center_content"
                    style="width:120px;overflow: hidden;text-overflow:ellipsis;white-space: nowrap;"
                    v-if="item.msgType == 1"
                  >
                    {{ item.message }}
                  </div>
                  <div
                    class="orderDetial_left_list_item_center_content"
                    style="width:120px;overflow: hidden;text-overflow:ellipsis;white-space: nowrap;"
                    v-if="item.msgType == 2"
                  >
                    [图片]
                  </div>
                  <div
                    class="orderDetial_left_list_item_center_content"
                    style="width:120px;overflow: hidden;text-overflow:ellipsis;white-space: nowrap;"
                    v-if="item.msgType == 3"
                  >
                    [视频]
                  </div>
                </div>
              </div>
              <div class="orderDetial_left_list_item_right">
                <span style="font-size:14px;color:#ccc">{{
                  item.add_time
                }}</span>
                <span class="nomessage" v-if="item.notReadCount != 0">{{
                  item.notReadCount
                }}</span>
              </div>
            </div>
          </div>
        </div>
        <div class="orderDetial_right">
          <div class="orderDetial_right_title">
            <!-- 处理人:客服
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            创建时间:{{ ruleForm.created_at }} -->
            <div style="margin-right:40px">
              当前客服人员:
              <b style="color:red">{{ curentMessage.curPeople }}</b>
            </div>
            需要转接的客服:&nbsp;&nbsp;&nbsp;
            <el-select
              v-model="value"
              placeholder="请选择转接的客服"
              @change="handlerSelect"
              :disabled="curentMessage.isCur == 2"
            >
              <el-option
                v-for="item in PeopleList"
                :key="item.userId"
                :label="item.petName"
                :value="item.userId"
              >
              </el-option>
            </el-select>
            <el-button
              type="success"
              style="width:100px;height:40px;margin:10px 0  0  10px"
              @click="handlerzhuan"
              >强制转接</el-button
            >
          </div>
          <div class="orderDetial_right_content">
            <div class="orderDetial_right_content_inner">
              <div
                v-for="item in userMessage"
                :key="item.id"
                class="content_line"
              >
                <div v-if="item.direction == 2" class="content_inner_left">
                  <!-- <div style="font-size: 14px; color: #b2b2b2">
                    {{ item.userName }} {{ item.add_time }}
                  </div> -->
                  <div class="orderDetial_left_list_item_left">
                    {{
                      item.userName == null
                        ? "未知"
                        : item.userName.substring(item.userName.length - 2)
                    }}
                  </div>

                  <div class="order_inner_text" v-if="item.msgType == 1">
                    {{ item.message }}
                  </div>
                  <viewer>
                    <img
                      v-if="item.msgType == 2"
                      :src="item.message"
                      alt=""
                      style="width: 80px; height: 80px; margin: 10px;"
                    />
                  </viewer>
                  <video
                    v-if="item.msgType == 3"
                    :src="item.message"
                    style="width: 80px; height: 80px; margin: 10px"
                  ></video>
                </div>
                <div v-if="item.direction == 1" class="content_inner_right">
                  <!-- <div style="font-size: 14px; color: #b2b2b2;float:right">
                    {{ item.userName }}
                    {{ item.add_time }}
                  </div> -->
                  <div class="order_inner_text" v-if="item.msgType == 1">
                    {{ item.message }}

                    <!-- <img
                      src="../../assets/images/icon.png"
                      style="width: 20px; height: 20px; float: right"
                      class="showiconIS"
                      @click="handlerDelMessage(item.id)"
                    /> -->
                  </div>
                  <viewer>
                    <img
                      v-if="item.msgType == 2"
                      :src="item.message"
                      alt=""
                      style="width: 80px; height: 80px; margin: 10px"
                    />
                  </viewer>
                  <video
                    v-if="item.msgType == 3"
                    :src="item.message"
                    controls
                    style="width: 200px; height: 200px; margin: 10px"
                  ></video>
                  <div class="orderDetial_left_list_item_left">
                    {{
                      item.userName == null
                        ? "未知"
                        : item.userName.substring(item.userName.length - 2)
                    }}
                  </div>
                </div>
              </div>
            </div>

            <div class="orderDetial_right_down">
              <el-form
                :model="messageForm"
                ref="messageForm"
                class="demo-ruleForm"
              >
                <el-form-item prop="message">
                  <el-input
                    v-model="messageForm.message"
                    class="sendMessage"
                    placeholder="请输入"
                    @input="handlerInput"
                    readonly
                    v-if="curentMessage.isCur == 2"
                  ></el-input>
                  <el-input
                    v-else
                    v-model="messageForm.message"
                    class="sendMessage"
                    placeholder="请输入"
                    @input="handlerInput"
                  ></el-input>

                  <img
                    :src="picMessage"
                    alt=""
                    style="width:50px;height:50px"
                    v-if="picMessage != ''"
                  />
                  <video
                    :src="videoMessage"
                    style="width:50px;height:50px"
                    v-if="videoMessage != ''"
                  ></video>
                </el-form-item>
                <div class="form_line">
                  <div style="width: 300px; display: flex; flex-direction: row">
                    <el-form-item
                      prop="picMessage"
                      style="margin-left: 30px; margin-right: 30px"
                    >
                      <ImageOrder
                        @getImage="handlerSuccess"
                        v-if="curentMessage.isCur != 2"
                      />
                    </el-form-item>
                    <el-form-item prop="videoMessage" class="orderVideo">
                      <Video
                        @getVideo="getVideo"
                        style="margin-right: 30px"
                        v-if="curentMessage.isCur != 2"
                      />
                    </el-form-item>
                  </div>
                  <el-form-item prop="message">
                    <el-button @click="sendMessage">发送</el-button>
                  </el-form-item>
                </div>
              </el-form>
            </div>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import ImageOrder from "../../components/ImageOrder";
import Video from "../../components/Video";
import {
  createChat,
  sendChat,
  getChatList,
  getChatDetail,
  getChangePeople,
  changePeople,
  readMsg,
  forceChangePeople
} from "../../utils/api";
export default {
  components: {
    ImageOrder,
    Video
  },
  data() {
    inject: ["reload"];
    return {
      labelPosition: "top",
      // 详情数据
      ruleForm: {
        appKey: "",
        name: "",
        phone: "",
        orderTitle: "",
        orderContent: "",
        picVideo: "",
        type: "",
        status: "",
        created_at: ""
      },
      // 用户发送消息的数据
      messageForm: {
        message: "",
        msgType: "1",
        fromId: ""
      },
      // 工单id
      orderID: "",
      websocket: null,
      // websock
      device_data: "",
      appKeydata: "",
      // 用户信息列表
      userMessage: [],
      // 后台信息列表
      adminMessage: [],
      // 文字的内容
      wordMessage: "",
      // 图片的内容
      picMessage: "",
      // 视频内容
      videoMessage: "",
      username: "",
      value: "",
      usermssageList: [],
      // 当前选中的聊天记录
      curentMessage: "",
      // 转接人员列表
      PeopleList: [],
      // 第一条聊天id
      firstMessageId: "",

      page: 1,
      all_page: 1

      // lockReconnect: false, //是否真正建立连接
      // timeout: 60 * 1000, // 1分钟一次心跳
      // timeoutObj: null, //心跳心跳倒计时
      // serverTimeoutObj: null, //心跳倒计时
      // // timeoutnum: null //断开 重连倒计时
    };
  },
  created() {
    this.orderID = window.sessionStorage.getItem("orderID");
    this.username = JSON.parse(
      window.sessionStorage.getItem("userInfo")
    ).petName;

    this.handleruser();
    this.handlergetChangePeople();

    // 调用websocket
    this.websocketTest();
  },
  mounted() {},
  destroyed() {
    // this.websocket.close(); //离开路由之后断开websocket连接
    // router.afterEach(route => {
    //   this.websocketonopen();
    // });
  },
  updated() {
    let msg = document.querySelector(".orderDetial_right_content_inner"); // 获取对象
    msg.scrollTop = msg.scrollHeight; // 滚动高度
  },
  methods: {
    refresh(done) {
      console.log(done);
      // setTimeout(() => {
      //   done();
      // }, 1500);
    },

    // 上传图片成功
    handlerSuccess(val) {
      let fileName = val.lastIndexOf("."); //取到文件名开始到最后一个点的长度
      let fileNameLength = val.length; //取到文件名长度
      let fileFormat = val.substring(fileName + 1, fileNameLength); //截
      this.picMessage = val;
    },
    // 输入框输入文字的时候
    handlerInput(val) {
      this.wordMessage = val;
    },
    // 获取视频地址
    getVideo(val) {
      this.videoMessage = val;
    },
    // 点击返回
    handlerBack() {
      this.$store.dispatch("delVisitedViews", this.$route).then(obj => {
        this.$router.push("/workOrderlist");
      });
    },
    // 点击强制转接
    handlerzhuan() {
      const params = {
        fromId: this.curentMessage.fromId
      };
      this.$confirm("该聊天转接强制转接给自己吗, 是否继续?", "转接客服", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          const params = {
            fromId: this.curentMessage.fromId
          };
          this.postRequest(forceChangePeople, params).then(res => {
            if (res.code == 200) {
              this.$message({
                type: "success",
                message: "转接客服成功!"
              });
              // this.handlerDetial();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消转接"
          });
        });
    },
    // 消息更新
    handlermessageCheck() {
      const params = {
        orderId: this.orderID,
        appKey: window.sessionStorage.getItem("appkey"),
        direction: 1
      };
      this.postRequest(messageCheck, params, "kefu").then(res => {});
    },
    // 点击发送信息
    sendMessage() {
      // if (this.messageForm.message == "") {
      //   return this.$message.error("请输入消息内容");
      // }
      // 判断是文字消息
      if (this.wordMessage != "") {
        if (this.messageForm.message == "") {
          return this.$message.error("请输入消息内容");
        }

        this.messageForm.msgType = 1;
        this.messageForm.message = this.wordMessage;
        this.messageForm.fromId = this.curentMessage.fromId;
        this.postRequest(sendChat, this.messageForm).then(res => {
          if (res.code == 200) {
            this.messageForm.message = "";
            // this.wordMessage();
            this.$refs.messageForm.resetFields();
            this.handlerDetialFirst();
          }
        });
      }
      // 判断是图片消息
      if (this.picMessage != "") {
        this.messageForm.msgType = 2;
        this.messageForm.message = this.picMessage;
        this.messageForm.fromId = this.curentMessage.fromId;

        this.postRequest(sendChat, this.messageForm).then(res => {
          this.picMessage = "";
          if (res.code == 200) {
            this.messageForm.message = "";
            this.picMessage = "";
            this.$refs.messageForm.resetFields();

            this.handlerDetialFirst();
          }
        });
      }
      // 判断是视频消息
      if (this.videoMessage != "") {
        this.messageForm.msgType = 3;
        this.messageForm.message = this.videoMessage;
        this.messageForm.fromId = this.curentMessage.fromId;

        this.postRequest(sendChat, this.messageForm).then(res => {
          if (res.code == 200) {
            this.messageForm.message = "";
            this.videoMessage = "";

            this.handlerDetialFirst();
          }
        });
      }
    },
    // // 回车发送消息
    // keyDown(e) {
    //   if (e.keyCode == 13) {
    //     this.sendMessage();
    //   }
    // },
    //  获取信息列表

    // 点击删除消息
    handlerDelMessage(id) {
      const params = {
        id: id,
        direction: 1
      };
      this.postRequest(messageDelete, params, "kefu").then(res => {
        if (res.code == 200) {
        }
      });
    },
    // 获取用户聊天列表
    handleruser() {
      const params = {
        pageNumber: this.page,
        pageSize: 9999
      };
      this.postRequest(getChatList, params).then(res => {
        if (res.code == 200) {
          this.usermssageList = res.data.list;
          if (res.data.count != 0) {
            this.firstMessageId = res.data.list[0].fromId;
            if (this.curentMessage == "") {
              this.curentMessage = res.data.list[0];
            }

            this.handlerDetialFirst();
          }
        }
      });
    },
    // 点击对应的消息
    handlerDetialFirst() {
      // 拿到当前选中的聊天记录
      const params = {
        pageNumber: 1,
        pageSize: 9999,
        fromId: this.firstMessageId
      };
      this.postRequest(getChatDetail, params).then(res => {
        if (res.code == 200) {
          this.userMessage = res.data.list;
        }
      });
    },
    // 点击对应的消息
    handlerDetial(info) {
      // 拿到当前选中的聊天记录
      this.curentMessage = info;

      this.postRequest(readMsg, {
        fromId: info.fromId
      }).then(res => {});

      const params = {
        pageNumber: 1,
        pageSize: 9999,
        fromId: info.fromId
      };
      this.postRequest(getChatDetail, params).then(res => {
        if (res.code == 200) {
          this.userMessage = res.data.list;
          const params = {
            pageNumber: 1,
            pageSize: 9999
          };
          this.postRequest(getChatList, params).then(res => {
            if (res.code == 200) {
              this.usermssageList = res.data.list;
              if (res.data.count != 0) {
                this.firstMessageId = res.data.list[0].fromId;
                // this.curentMessage = res.data.list[0];
              }
            }
          });
        }
      });
    },
    // 获取可转接的客服人员
    handlergetChangePeople() {
      this.postRequest(getChangePeople).then(res => {
        if (res.code == 200) {
          this.PeopleList = res.data;
        }
      });
    },
    // 选择转接的客服
    handlerSelect(val) {
      console.log(val);
      this.$confirm("该聊天转接给其他客服, 是否继续?", "转接客服", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          const params = {
            changeToId: val,
            fromId: this.curentMessage.fromId
          };
          this.postRequest(changePeople, params).then(res => {});
          this.$message({
            type: "success",
            message: "转接客服成功!"
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消转接"
          });
        });
    },
    // /********** websocket  ****** */
    websocketTest() {
      //初始化websocket
      // var url="ws://123.207.89.57:8282";
      var url = " wss://tcp.wadd.vip/wss";
      this.websocket = new WebSocket(url);
      this.websocket.onmessage = this.websocketonmessage;
      this.websocket.onopen = this.websocketonopen;
      this.websocket.onerror = this.websocketonerror;
      // this.websocket.onclose = this.websocketclose;
    },
    websocketonopen() {
      console.log("连接成功");
      if (this.websocket.readyState == 1) {
        var data = {
          type: "login",
          device_id: "socketChat" + window.sessionStorage.getItem("userId") + 2
        };
        var arr = JSON.stringify(data);
        // console.log(arr);
        this.websocket.send(arr);
      }
    }, //连接成功
    websocketonerror() {
      console.log("连接失败");
    }, //连接失败
    websocketclose() {
      console.log("断开连接");
    },
    //数据接收
    websocketonmessage(data) {
      // console.log(data);
      if (JSON.parse(data["data"])["type"] == "login") {
        const clientId = JSON.parse(data["data"])["client_id"];
        window.sessionStorage.setItem("messageClentID", clientId);

        setInterval(() => {
          var data1 = {
            type: "ping"
          };
          // console.log(data1);
          var arr1 = JSON.stringify(data1);
          this.websocket.send(arr1);
        }, 60000);
        //拿到client id
        this.postRequest(createChat, { client_id: clientId }).then(res => {});
      }
      if (JSON.parse(data["data"])["type"] == "pong") {
        if (
          JSON.parse(data["data"])["client_id"] ==
          window.sessionStorage.getItem("messageClentID")
        ) {
        } else {
          this.websocketTest();
        }
      }
      if (JSON.parse(data["data"])["type"] == "chat") {
        //调消息接口

        this.handleruser();
      }
      //收到消息会刷新心跳检测，如果一直收到消息，就推迟心跳发送
      this.heatBeat();
    },
    websocketsend(data) {
      // this.websocket.send(JSON.stringify(data));
      this.websocket.send(data);
    },
    reconnect() {
      // if(this.lockReconnect){       //这里很关键，因为连接失败之后之后会相继触发 连接关闭，不然会连接上两个 WebSocket
      //     return
      // }
      // this.lockReconnect = true;
      // this.reconnectData && clearTimeout(this.reconnectData);
      // this.reconnectData = setTimeout(()=>{
      //     this.initWebSocket();
      //     this.lockReconnect = false;
      // },5000)
    },
    heatBeat() {
      // this.timeoutObj && clearTimeout(this.timeoutObj);
      // this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
      // this.timeoutObj = setTimeout(()=>{
      //     this.websocketsend({type:'心跳检测'})   //根据后台要求发送
      //     this.serverTimeoutObj = setTimeout(()=> {
      //         this.websock.close();       //如果  5秒之后我们没有收到 后台返回的心跳检测数据 断开socket，断开后会启动重连机制
      //     }, 5000);
      // }, this.timeout)
    },
    destroyed() {
      // this.lockReconnect = true;
      // this.websock.close()                   //离开路由之后断开websocket连接
      // clearTimeout(this.reconnectData);      //离开清除 timeout
      // clearTimeout(this.timeoutObj);         //离开清除 timeout
      // clearTimeout(this.serverTimeoutObj);   //离开清除 timeout
    }
  }
};
</script>

<style lang="less">
.orderDetial {
  overflow-y: auto;
  .orderDetial_top {
    font-size: 20px;
    height: 57px;
    background-color: #fff;
    line-height: 57px;
  }
  .orderDetial_inner {
    display: flex;
    flex-direction: row;
    justify-content: space-between;

    .orderDetial_left {
      border: 1px solid #eeeeee;

      // flex: 1.5;
      width: 300px;
      // height: 843px;
      overflow: scroll;
      .orderDetial_left_list {
        display: flex;
        flex-direction: column;
        line-height: 40px;
        border-bottom: 1px solid #cccccc;
        .orderDetial_left_list_item {
          overflow: hidden;
          display: flex;
          flex-direction: row;
          line-height: 40px;
          justify-content: space-between;
          .orderDetial_left_list_item_right_x {
            display: flex;
            flex-direction: row;
            .orderDetial_left_list_item_left {
              width: 40px;
              height: 40px;
              border-radius: 50%;
              margin-top: 20px;
              margin-left: 10px;
              background: #4f97f3;
              margin-right: 10px;
              font-size: 12px;
              color: #fff;
              text-align: center;
            }
            .orderDetial_left_list_item_center {
              display: flex;
              flex-direction: column;
              line-height: 26px;
              margin-top: 20px;
              .orderDetial_left_list_item_center_name {
                font-size: 16px;
                font-weight: 500;
              }
              .orderDetial_left_list_item_center_content {
                font-size: 12px;
                color: #b5b5b5;
              }
            }
          }

          .orderDetial_left_list_item_right {
            display: flex;
            flex-direction: column;
            align-items: flex-end;
            margin-top: 11px;
            .nomessage {
              width: 20px;
              height: 20px;
              border-radius: 50%;
              background-color: red;
              font-size: 12px;
              text-align: center;
              line-height: 20px;
              color: #fff;
              display: inline-block;
            }
          }
        }
        //鼠标移入
        .orderDetial_left_list_item:hover {
          cursor: pointer;
        }
      }
    }
    .orderDetial_right {
      flex: 2;
      border: 1px solid #cccccc;
      .orderDetial_right_title {
        padding-left: 20px;
        line-height: 60px;
        height: 60px;
        border-bottom: 1px solid #707070;
        display: flex;
        flex-direction: row;
      }
      .orderDetial_right_content {
        position: relative;
        height: 580px;
        min-height: 500px;

        .orderDetial_right_content_inner {
          height: 400px;
          overflow: scroll;
          .content_line {
            width: 99%;
            height: 100px;
            margin: 5px 0px;
            clear: both;

            .content_inner_left {
              float: left;
              margin: 4px;
              display: flex;
              flex-direction: row;
              .orderDetial_left_list_item_left {
                width: 40px;
                height: 40px;
                border-radius: 50%;
                margin-top: 20px;
                margin-left: 10px;
                background: #4f97f3;
                margin-right: 10px;
                font-size: 12px;
                color: #fff;
                text-align: center;
                line-height: 40px;
              }
              .order_inner_text {
                // width: 300px;
                max-width: 300px;
                border: 1px solid #d4d4d4;
                text-align: left;
                padding: 7px;
                color: #000;
                border-radius: 5px;
                line-height: 25px;
                margin-top: 20px;
                word-break: break-all;
              }
            }
            .content_inner_right {
              float: right;
              display: flex;
              flex-direction: row;
              .orderDetial_left_list_item_left {
                width: 40px;
                height: 40px;
                border-radius: 50%;
                margin-top: 20px;
                margin-left: 10px;
                background: #4f97f3;
                margin-right: 10px;
                font-size: 12px;
                color: #fff;
                text-align: center;
                line-height: 40px;
              }
              .order_inner_text {
                // width: 300px;
                max-width: 300px;

                border: 1px solid #d4d4d4;
                text-align: left;
                padding: 7px;
                color: #000000;
                line-height: 25px;
                border-radius: 5px;
                margin-top: 20px;
                background: #c9e7ff;
              }
            }
          }
        }
        .orderDetial_right_down {
          border-top: 1px solid #707070;
          width: 100%;
          position: absolute;
          bottom: 0;
          left: 0;
          .demo-ruleForm {
            .el-input /deep/ .el-input__inner {
              width: 100%;
              height: 100px;
              border: none;
            }
            .form_line {
              display: flex;
              flex-direction: row;
              justify-content: space-between;
            }
          }
        }
      }
    }
  }
}
</style>
